// pages/home/home.js
import {
  showText
} from "../../utils/util";
import {
  bannerList,
  getEntryConfigReq
} from '@/api/home'
import {
  inviteAwardList
} from '@/api/register'
import {
  spaList
} from '@/api/spa'
import {
  getgemomemberuser,
} from '@/api/auth'
import {
  getMemberLevel
} from '@/api/my'
import {
  getTaskStatus
} from "@/api/task/task.service";

const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgUri: getApp().globalData.imgUri,
    cdn: getApp().globalData.cdn,
    bottomInset: 20,
    pageCurrent: 0,
    swiperIndex: 0,
    cardOpenIndex: 0,
    phone: '',
    spa_list: [],
    autoplayInfoSwiper: false,
    bannerListData: [],
    isShowDialogHomeTask: false,
    banner_o: {
      moduleType: 'HOMEPAGE',
      status: 0
    },
    PointTaskList: [],

    percent: 0 //banner预加载百分比
  },
  topage() {
    wx.navigateTo({
      url: '/pages/register/register',
    })
  },
  goToSpa(e) {
    let {
      id
    } = e.currentTarget.dataset
    var url = '/pages/spa/spa?id=' + id;
    wx.setStorageSync('module_url', url);
    var phone = wx.getStorageSync('phone');
    if (phone) {
      wx.navigateTo({
        url: url
      })
    } else {
      wx.navigateTo({
        url: '/pages/register/register'
      })
    }
  },
  goToUrl(e, status) {
    console.log(e, status);
    let {
      url
    } = e.currentTarget.dataset

    wx.setStorageSync('module_url', url);
    if (url && (status === undefined || status)) {
      var phone = wx.getStorageSync('phone');
      if (phone) {
        wx.navigateTo({
          url: url,
        })
      } else {
        wx.navigateTo({
          url: '/pages/register/register'
        })
      }
    } else {
      showText('您好，该活动暂未开始，敬请期待！')
    }
  },

  goToBuyback(e) {
    getEntryConfigReq().then(res => {
      if (res.code == 200)
        this.goToUrl(e, res.msg == 'true' ? true : false);
      else showText("状态错误")
    });
  },

  goToShare() {
    let url = "/pages/invite/invite";
    var phone = wx.getStorageSync('phone');
    if (phone) {
      let o = {
        pageNum: 1,
        pageSize: 20,
      }
      inviteAwardList(o).then(res => {
        if (res.code == 200) {
          var listDataLength = res.data.listData.length;
          if (listDataLength > 0) {
            wx.navigateTo({
              url: '/pages/inviteSuccess/inviteSuccess'
            })
          } else {
            wx.navigateTo({
              url: url
            })
          }
        }
      });
    } else {
      wx.navigateTo({
        url: '/pages/register/register'
      })

    }
  },
  bindchangeSwiper(e) {
    this.setData({
      pageCurrent: e.detail.current,
      cardOpenIndex: e.detail.current == 1 ? 0 : this.data.cardOpenIndex
    })
  },
  bindchangeSwiper1(e) {
    this.setData({
      swiperIndex: e.detail.current
    })
  },
  changeCardIndex(e) {
    let {
      index
    } = e.currentTarget.dataset
    this.setData({
      cardOpenIndex: index
    })
  },

  /** 子组件更新任务列表数据 */
  updateListByChild(e) {
    this.setData({
      PointTaskList: e.detail
    })
  },

  /** 打开积分任务弹窗 */
  showDialogPoint() {
    getTaskStatus().then(res => {
      this.setData({
        PointTaskList: res
      })
      this.setData({
        isShowDialogHomeTask: true
      })
    });
  },

  /** 关闭积分任务弹窗 */
  hideDialogPoint() {
    this.setData({
      isShowDialogHomeTask: false
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let t = this;
    const systemInfo = wx.getWindowInfo();
    const bottomInset = Math.abs(systemInfo.safeArea.bottom - systemInfo.windowHeight);
    console.log('Bottom inset: ', bottomInset);
    t.setData({
      bottomInset,
      autoplayInfoSwiper: true
    });

    let phone = wx.getStorageSync('phone');
    let memberLevel = wx.getStorageSync('memberLevel');
    if (phone && memberLevel) {
      let banner_o = t.data.banner_o;
      banner_o.gemoLevel = memberLevel.currentLevelEnum;
      banner_o.haveCommonBanner = true;
      t.get_banner(banner_o);
    } else {
      t.get_memberlevel();
    }

  },
  onShow() {
    this.setData({
      autoplayInfoSwiper: true
    })

    if (this.data.isShowDialogHomeTask) this.showDialogPoint(); //解决离开弹窗做任务再返回此页后卡片内容不更新的问题
  },
  get_memberlevel() {
    let t = this;
    getMemberLevel({}).then((level) => {
      if (level.code == 200) {
        console.log("memberLevel");
        if (level.data) {
          wx.setStorageSync('memberLevel', level.data);
        }

        t.get_getgemomemberuser();
      }
    });
  },
  get_getgemomemberuser() {
    let t = this;
    getgemomemberuser({}).then(res => {
      if (res.code == 200) {
        console.log("momemberuser");
        wx.setStorageSync('getgemomemberuser', res.data);
        let banner_o = t.data.banner_o;
        if (res.data.phonenumber) {
          wx.setStorageSync('phone', res.data.phonenumber);
          banner_o.gemoLevel = wx.getStorageSync('memberLevel').currentLevelEnum
          banner_o.haveCommonBanner = true
        } else {
          banner_o.onlyCommonBanner = true
        }
        t.get_banner(banner_o);

        wx.setStorageSync('openid', res.data.openid);
        app.Monitor.getStoreInit({
          openid: res.data.openid
        });
      }
    });
  },

  onLoadingFinish() {
    // console.log('加载完成', this.bannerList);
    this.setData({ bannerListData: this.bannerList })
  },

  get_banner(o) {
    const fs = wx.getFileSystemManager();
    console.log(fs.saveFile);
    let num = 0;
    bannerList(o).then(async res => {
      if (res.code == 200) {
        this.bannerList = res.rows || [];
        const count = this.bannerList.length;
        this.bannerList.forEach((item, index) => {
          const fileName = item.resourceUrl.replace(/\//g, "_");
          const filePath = `${wx.env.USER_DATA_PATH}/${fileName}`;
          fs.access({
            path: filePath,
            success: () => {
              item.srcLocal = filePath
              this.setData({ percent: ++num / count * 100 });
            },
            fail: () => {
              wx.downloadFile({
                url: `${this.data.cdn}${item.resourceUrl}`,
                success: (res) => {
                  if (res.statusCode === 200) {
                    fs.saveFile({
                      tempFilePath: res.tempFilePath,
                      filePath,
                      success: () => item.srcLocal = filePath,
                      complete: () => this.setData({ percent: ++num / count * 100 })
                    });
                  }
                  else showText("图片下载失败");
                },
                fail: (err) => showText("图片下载失败")
              });
            }
          });
        })

        this.spa_list();
      } else showText("数据加载失败:" + res.msg);
    });
  },
  spa_list() {
    spaList().then(res => {
      if (res.code == 200) {
        let data = res.data;
        this.setData({
          spa_list: data
        });
      }
    });
  },
  onHide() {
    let t = this;
    setTimeout(function () {
      t.setData({
        swiperIndex: 0,
        cardOpenIndex: 0,
        autoplayInfoSwiper: false
      })
    }, 500);
  },
  onShareAppMessage() {
    return {
      title: getApp().globalData.share_title,
      path: getApp().globalData.share_url,
      imageUrl: getApp().globalData.share_image,
    }
  }
})